package cn.sciento.starter.keyencrypt.json;

import cn.sciento.core.exception.CommonException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.Module;
import cn.sciento.starter.keyencrypt.core.IEncryptionService;

public class CryptoModule extends Module {
  public static final String GROUP_ID = "org.srm";
  
  public static final String ARTIFACT_ID = "jackson-json-crypto";
  
  private EncryptedSerializerModifier serializerModifierModifier;
  
  private EncryptedDeserializerModifier deserializerModifierModifier;
  
  public CryptoModule addEncryptionService(IEncryptionService encryptionService) {
    this.serializerModifierModifier = new EncryptedSerializerModifier(encryptionService);
    this.deserializerModifierModifier = new EncryptedDeserializerModifier(encryptionService);
    return this;
  }
  
  public String getModuleName() {
    return "jackson-json-crypto";
  }
  
  public Version version() {
    return new Version(1, 0, 0, null, "org.srm", "jackson-json-crypto");
  }
  
  public void setupModule(Module.SetupContext context) {
    if (null == this.serializerModifierModifier || null == this.deserializerModifierModifier)
      throw new CommonException("Crypto module not initialised with an encryption service");
    context.addBeanSerializerModifier(this.serializerModifierModifier);
    context.addBeanDeserializerModifier(this.deserializerModifierModifier);
  }
}
